<template>
	<view>
		<navbar title="下载管理">
			<view>
				<u-icon @click="clear()" name="trash" color="#373737" size="30"></u-icon>
			</view>
		</navbar>
		<view v-for="(item,index) in downloadList">
			<view @click="btn(item.filename,index,item.downloadedSize,item.totalSize)"
				style="display: flex;padding: 10px;background-color: white;align-items: center;justify-content: space-between;">
				<image :src="item.options.icon" style="width: 50px;height: 50px;border: 99px;"></image>
				<view style="margin: 10px;flex: 1;">
					<u--text size="17" :text="getname(item.filename)" lines="1"></u--text>
					<u--text size="14" color="#909699" :text="gsbytes(item.totalSize)" lines="1"></u--text>
				</view>
				<view style="display: flex;align-items: center;">
					<u-button type="primary" size="small" :text="progress(item.downloadedSize,item.totalSize)"
						shape="circle" style="width: 60px;"></u-button>
				</view>
			</view>
			<u-divider style="margin: 0px;"></u-divider>
		</view>
		<u-empty v-if="downloadList.length==0" mode="list" text="下载列表为空">
		</u-empty>
		<view style="height: 40px;">

		</view>
		<view
			style="position: fixed;bottom: 0px;left: 0;right: 0;text-align: center;background-color: #eeeeee;line-height: 30px;color: #909699;">
			<p style="font-size: 14px;">文件保存路径为Android/data/com.x2.ink/downloads/</p>
		</view>
	</view>
</template>
<script>
	import store from '@/store/index.js';
	export default {
		data() {
			return {
				downloadList: [],
			};
		},
		onReady() {
			let op = store.state.download
			console.log(store.state.download);
			this.down(op.url, op.name, op.icon, op.id)
			var that = this
			plus.downloader.enumerate(function(tasks) {
				that.downloadList = tasks.reverse()
			}, -1);
		},
		methods: {
			progress(a, b) {
				var temp = ((a / b) * 100).toFixed(1)
				if (temp == 100) {
					return "打开"
				} else {
					return temp + '%'
				}
			},
			getname(name) {
				return name.split('/')[1]
			},
			btn(filename, index, a, b) {
				if (((a / b) * 100).toFixed(0) == 100) {
					uni.openDocument({
						filePath: filename
					})
				}
			},
			clear() {
				plus.downloader.clear(-1)
				this.downloadList = []
				plus.nativeUI.toast("清除成功")
			},
			down(url, name, icon, id) {
				var index = this.downloadList.length
				var time = new Date()
				var task = plus.downloader.createDownload(url, {
					filename: "_downloads/" + name,
					icon: icon,
					id: id
				}, (res) => {
					plus.nativeUI.toast(that.getname(res.filename) +
						"下载成功!保存路径为Android/data/com.x2.ink/downloads/" + that.getname(res.filename))
				});
				task.start();
				var that = this
				task.addEventListener("statechanged", (progress, status) => {
					var temp = ((progress.downloadedSize / progress.totalSize) * 100).toFixed(10)
					if (temp != 100) {
						plus.downloader.enumerate(function(tasks) {
							that.downloadList = tasks.reverse()
						}, -1);
					}
				}, false)
			},
		},
	}
</script>